package com.dragon.loan.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.dragon.account.entity.CmAppConsumptioninst;
import com.dragon.account.entity.PrCodeTable;
import com.dragon.account.repository.CmAppConsumptioninstRepository;
import com.dragon.account.repository.PrCodeTableRepository;
import com.dragon.account.service.PrCodeTableService;
import com.dragon.app.marvel2.NewMarvelCoreService;
import com.dragon.app.ykd.service.ClientAppService;
import com.dragon.common.entity.search.Searchable;
import com.dragon.common.repository.mybatis.paginator.domain.Order;
import com.dragon.common.repository.mybatis.paginator.domain.PageBounds;
import com.dragon.common.repository.mybatis.paginator.domain.PageList;
import com.dragon.common.util.PropertiesLoadUtil;
import com.dragon.common.utils.PageListJsonUtils;
import com.dragon.loan.common.Constants;
import com.dragon.loan.entity.AcApplyEnvironmentInfo;
import com.dragon.loan.entity.AcCaseStatusTrace;
import com.dragon.loan.entity.AcLoanApplyBxInfo;
import com.dragon.loan.entity.AcLoanApplyInfo;
import com.dragon.loan.entity.AcLoanApplyLinkman;
import com.dragon.loan.entity.McamAcLoanApplyBdInfo;
import com.dragon.loan.entity.McamAcLoanApplyImageInfo;
import com.dragon.loan.entity.McamLoanApplyInfo;
import com.dragon.loan.repository.AcApplyEnvironmentInfoMapper;
import com.dragon.loan.repository.AcCaseStatusTraceRepository;
import com.dragon.loan.repository.AcLoanApplyInfoRepository;
import com.dragon.loan.repository.DecisionGeneralRuleMapper;
import com.fintech.common.util.ProductUtils;
import com.fintech.common.util.PropertiesUtils;
import com.fintech.common.vo.FintechResult;
import com.fintech.user.entity.RealNameAuthentication;
import com.fintech.user.entity.User;
import com.fintech.user.entity.UserChannelInfo;
import com.fintech.user.service.RealNameAuthenticationService;
import com.fintech.user.service.UserChannelInfoService;
import com.fintech.user.service.UserService;
import com.marvels.common.utils.MarvelsLogUtil;

/**
 * 贷款信息服务实现类
 * 
 * @author xiaoyifan
 * @since 2017-02-06s
 */
@Service
public class LoanInfoService implements LoanInfoIDragonService {

	private static final String CASE_STATUS_TRACE_COCE = "PROC_STS_DSC";

	private Integer LOAN_ID_SEQ = 0;

	private static final String ONLINE_PATTERN_TYPE = "A";
	private static final String OFFLINE_PATTERN_TYPE = "B";
	/** 祁安保险的标识付 */
	public static final String  QI_AN_BX = "qabx";

	@Autowired
	private AcLoanApplyInfoServiceImpl acLoanApplyInfoService;
	@Autowired
	private PrCodeTableRepository prCodeTableRepository;
	@Autowired
	private AcCaseStatusTraceRepository acCaseStatusTraceRepository;
	@Autowired
	private AcLoanApplyInfoRepository acLoanApplyInfoRepository;
	@Autowired
	private CmAppConsumptioninstRepository appConsumptioninstRepository;
	@Autowired
	private GetCommonParamIService getCommonParamIService;
	@Autowired
	private com.dragon.paymentplan.dao.MpFundPricingMapper mpFundPricingMapper;
	@Autowired
	private AcApplyEnvironmentInfoMapper acApplyEnvironmentInfoMapper;
	@Autowired
	private PrCodeTableService prCodeTableService;
	@Autowired
	private RealNameAuthenticationService realNameAuthenticationService;
	@Autowired
	private AcCaseStatusTraceService acCaseStatusTraceService;
	@Autowired
	private AcLoanApplyBxInfoService acLoanApplyBxInfoService;
	@Autowired
	private AcLoanApplyLinkmanService acLoanApplyLinkmanService;
	@Autowired
	private NewMarvelCoreService newMarvelCoreService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserChannelInfoService userChannelInfoService;
	@Autowired
	private ClientAppService clientAppService;
	@Autowired
	private AcLoanApplyInfoExtDragonService acLoanApplyInfoExtDragonService;
	@Autowired
	AppConsumptioninstService appConsumptioninstService;
	@Autowired
	private DecisionGeneralRuleMapper decisionGeneralRuleMapper;
	@Value("${loanid.prefix}")
	private String prefix ;
	
	@Value("${assure.on.off}")
	private String assureOnOff ;
	
	@Value("${prefix_url_switch}")
	private String prefixUrlSwitch;
	@Override
	public AcLoanApplyInfo queryLoanBasicInfo(String loanId) {
		if (!StringUtils.hasText(loanId)) {
			return null;
		}
		return acLoanApplyInfoService.findByLoanId(loanId);
	}
	
	@Override
	@Deprecated
	public void input(AcLoanApplyInfo acLoanApplyInfo) {

		if (acLoanApplyInfo == null) {
			MarvelsLogUtil.getInstance().info("贷款申请请求对象空");
			return;
		}
		MarvelsLogUtil.getInstance().info("************贷款申请请求数据:"+JSON.toJSON(acLoanApplyInfo));
		
		//1 验证（包括非空和业务属性）
		
		//1.1 loanId不能为空，检查是否忘生成全局唯一业务标识
		String loanId = acLoanApplyInfo.getLoanId();//贷款申请id
		if (!StringUtils.hasText(loanId)) {
			throw new RuntimeException("贷款申请编号不能为空");
		}
		
		//2 判断是新增贷款还是修改信息，分别进行不同的处理
		AcLoanApplyInfo info = acLoanApplyInfoService.findByLoanId(loanId);// 贷款申请包括申请信息、客户基本信息、客户工作信息、联系人信息、保单信息，分多次将信息提交录入
		List<AcLoanApplyLinkman> acLoanApplyLinkmans = acLoanApplyInfo.getAcLoanApplyLinkmans();// 联系人信息
		List<AcLoanApplyBxInfo> acLoanApplyBxInfos = acLoanApplyInfo.getAcLoanApplyBxInfos();// 保单信息

		//2.1  如果是新增贷款
		if (info == null) {
			try {
				acLoanApplyInfoService.apply(acLoanApplyInfo);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().info("保存贷款信息出错,loanId="+loanId);
				throw new RuntimeException(e);
			} 
			//2.2  如果是分享写入的草稿则更新进行信息表及保存其他数据
		} else if ("-1".equals(info.getStatus())) {
			acLoanApplyInfo.setStatus(Constants.LOAN_STATUS_J01);
			acLoanApplyInfo.setUpdateTime(new Date());
			acLoanApplyInfoService.update(acLoanApplyInfo);
			PrCodeTable prCodeTable = prCodeTableService.getCodeTable("PROC_STS_DSC",Constants.LOAN_STATUS_J01);
			if (null != prCodeTable) {
				acCaseStatusTraceService.saveCaseStatusTrace(loanId, prCodeTable.getDesc(), new Date(), Constants.LOAN_STATUS_J01);
			}
		} else {//2.3 如果是修改(此处逻辑怪异，后续本方法会去掉，按照具体场景修改为新增贷款，修改贷款，保存联系人，保存保单信息4个接口)
			if (!CollectionUtils.isEmpty(acLoanApplyLinkmans))//只保存联系人信息 
					acLoanApplyLinkmanService.save(loanId, acLoanApplyLinkmans);
				else if (!CollectionUtils.isEmpty(acLoanApplyBxInfos)) //只保存保单信息
					acLoanApplyBxInfoService.save(loanId, acLoanApplyBxInfos);
				else //修改贷款信息
				acLoanApplyInfoService.updateApply(acLoanApplyInfo);
		}
	}
	
	@Override
	public boolean updateLoanStatus(String loanId, String status) {
		MarvelsLogUtil.getInstance().info("修改贷款申请loanId:"+ loanId+"状态为status:"+status);
		if (!StringUtils.hasText(loanId) || !StringUtils.hasText(status)) {
			return false;
		}

		// 查询是否需要记案件状态流水
		PrCodeTable prCodeTable = queryProgressRemark(status);
		// 更新贷款申请状态
		AcLoanApplyInfo acLoanApplyInfo = new AcLoanApplyInfo();
		acLoanApplyInfo.setLoanId(loanId);
		acLoanApplyInfo.setStatus(status);
		acLoanApplyInfo.setUpdateTime(new Date());
		if (Constants.LOAN_STATUS_Z00.equals(status)) {
			acLoanApplyInfo.setProcessAppTime(new Date());
		} else if (Constants.LOAN_STATUS_A00.equals(status) || Constants.LOAN_STATUS_A01.equals(status)) {
			acLoanApplyInfo.setClearDateAct(new Date());
		} else if (Constants.LOAN_STATUS_J00.equals(status)) {
			acLoanApplyInfo.setApplyTime(new Date());
		}
		int updateCount = acLoanApplyInfoService.updateByLoanId(acLoanApplyInfo);
		if (updateCount == 1) {
			if (null != prCodeTable) {
				// 查询最近一笔的状态流水的状态
				AcCaseStatusTrace acCaseStatusTrace = acCaseStatusTraceRepository.selectLastRecord(loanId);
				if (null == acCaseStatusTrace || !status.equals(acCaseStatusTrace.getStatus())) {
					// 记案件状态流水
					acCaseStatusTraceService.saveCaseStatusTrace(loanId, prCodeTable.getDesc(), new Date(), status);
				}
			}
			// 进件业务流程日志
			/*
			 * try { loanLog(loanId, status); } catch (Exception e) {
			 * e.printStackTrace(); }
			 */
			return true;
		}
		return false;
	}
	
	@Override
	public String selectCustApplyingLoanId(String identityCard) {
		return acLoanApplyInfoRepository.selectCustApplyingLoanId(identityCard);
	}
	
	@Override
	public Map<String, Object> queryDebt(String loanid) {
		return acLoanApplyInfoRepository.queryDebt(loanid);
	}
	
	@Override
	public List<Map<String, String>> borrowList(String userInfo) {
		return acLoanApplyInfoRepository.borrowList(userInfo);
	}
	
	@Override
	public String selectCustApplyingStatus(String identityCard) {
		return acLoanApplyInfoRepository.selectCustApplyingStatus(identityCard);
	}
	
	@Override
	public List<Map<String, Object>> querySettleLoan(String identityCardNo) {
		return acLoanApplyInfoRepository.querySettleLoan(identityCardNo);
	}
	
	@Override
	public boolean isPassRule(String custIdCard, Integer days) {
		int count = acLoanApplyInfoRepository.isPassRule(custIdCard, days);
		if(count > 0){
			return false;
		}
		return true;
	}
	
	/**
	 * 如果返回为null 则未命中黑名单 Description
	 * 
	 * @author shan
	 * @date 2018年6月19日
	 */
	@Override
	public String blackListVerifyNew(String identityCard, String mobile) {
		/*Long minBlacklistId = acLoanApplyInfoRepository.getblackListIdByIdCard(identityCard);
		// 本地黑名单
		if (minBlacklistId != null) {//不为空一定是命中了黑名单
			if(minBlacklistId.longValue() < Long.valueOf(PropertiesLoadUtil.getPropertiesValue("new_blacklisi_start_id", "application.properties")).longValue()) {
				return "localBlacklist";//如果id小于新增黑名单的起始ID则为老的，否则标识为命中新的黑名单
			}else {
				return "SjdBlacklist";
			}
		}*/
		
		Long minBlacklistId = acLoanApplyInfoRepository.getblackListIdByMobile(mobile);
		// 本地黑名单
		if (minBlacklistId != null) {//不为空一定是命中了黑名单
			if(minBlacklistId.longValue() < Long.valueOf(PropertiesUtils.getString("new_blacklisi_start_id", "application.properties")).longValue()) {
				return "localBlacklist";//如果id小于新增黑名单的起始ID则为老的，否则标识为命中新的黑名单
			}else {
				return "SjdBlacklist";
			}
		}
		
		// 通讯录黑名单
		int localMobileBlack = acLoanApplyInfoRepository.findMobileBlackByIdCard(identityCard);
		if (localMobileBlack > 0) {
			return "addressBookBlacklist";
		}
		int blackCount = acLoanApplyInfoRepository.findMobileNumBlackByIdCard(mobile);
		if (blackCount > 0) {
			return "addressBookBlacklist";
		}
//		/*
//		 * 对于下表拒绝原因拒绝的客户，需永不准入 LA02 本地黑名单拒绝 LA05 本地联系人黑名单拒绝 NA01 极光黑名单拒绝 NF01
//		 * 上海资信逾期不符 NH01 百融特殊名单拒绝 NH05 百融本人法院涉案
//		 */
//		int findRefuseByIdCard = acLoanApplyInfoRepository.findRefuseByIdCard(identityCard);
//		if (findRefuseByIdCard > 0) {
//			return "decisionRulesBlacklist";
//		}
		return null;
	}
	
	@Override
	public String generateLoanId() {
		return loanIdGenerator();
	}

	private synchronized String loanIdGenerator() {
		// LOANID前缀
		if (StringUtils.isEmpty(prefix)) {
			// 10开头表示蚂蚁贷
			prefix = "10";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
		StringBuilder sb = new StringBuilder(prefix);
		if (LOAN_ID_SEQ > 99) {
			LOAN_ID_SEQ = 0;
		}
		// 2位自增长
		String autoSeq = String.format("%02d", LOAN_ID_SEQ);
		sb.append(sdf.format(new Date())).append(autoSeq);
		LOAN_ID_SEQ++;
		return sb.toString();
	}
	
	@Override
	public List<Map<String, String>> selectCustApplyingStatus(String identityCard, String classify) {
		return acLoanApplyInfoRepository.selectCustApplyingStatus2(identityCard, classify);
	}

	@Override
	public void insertAcApplyEnvironmentInfo(AcApplyEnvironmentInfo acApplyEnvironmentInfo) {
		acApplyEnvironmentInfoMapper.insertSelective(acApplyEnvironmentInfo);
	}
	
	@Override
	public McamLoanApplyInfo synchronizeLoanApplyInfo(String loanId) {
		MarvelsLogUtil.getInstance().info("============LoanInfoService.synchronizeLoanApplyInfo start============");
		// TODO 自动生成的方法存根
		McamLoanApplyInfo info = new McamLoanApplyInfo();
		AcLoanApplyInfo ac = acLoanApplyInfoService.findByLoanId(loanId);
		//查询用户信息
		User user = userService.queryUserById(Integer.parseInt(ac.getUserId()));
		//获取渠道信息
		MarvelsLogUtil.getInstance().info("============LoanInfoService.synchronizeLoanApplyInfo channelCode:" + user.getChannelCode() + "============");
		if(StringUtils.isEmpty(user.getChannelCode())){
			info.setChannelName("自然流量");
			info.setChannel("zrll");
		}else{
			UserChannelInfo userChannelInfo = userChannelInfoService.selectChannelInfoByCode(user.getChannelCode());
			MarvelsLogUtil.getInstance().info("============LoanInfoService.synchronizeLoanApplyInfo userChannelInfo:" + com.alibaba.fastjson.JSONObject.toJSONString(userChannelInfo) + "============");
			if(userChannelInfo != null){
				info.setChannelName(userChannelInfo.getChannelName());
				info.setChannel(userChannelInfo.getChannelCode());
			}
		}
		
		try {
			MarvelsLogUtil.getInstance().info("============LoanInfoService.synchronizeLoanApplyInfo 扩展信息同步," + loanId + "============");
			String virLaonId = loanId;
			FintechResult result = clientAppService.getThirdLoanId(loanId);
			MarvelsLogUtil.getInstance().info("============获取复贷loan结果：" + com.alibaba.fastjson.JSONObject.toJSONString(result));
			if(result.getData() != null){
				virLaonId = result.getData().toString();
			}
			Map<String, String> data = acLoanApplyInfoExtDragonService.queryExtInfoByLoanId(virLaonId);
			if(data != null){
				MarvelsLogUtil.getInstance().info("loanId[" + loanId + "]，获取进件扩展信息结果：" + com.alibaba.fastjson.JSONObject.toJSONString(data));
				info.setZmsCore(data.get("zms_core"));
				info.setAlipayAuth(data.get("alipay_auth"));
				info.setOperatorAuth(data.get("operator_auth"));
				info.setHuabaiLimit(data.get("huabai_limit"));
				info.setIsFace(data.get("is_face"));
				info.setIsVerify(data.get("is_verify"));
			}else{
				MarvelsLogUtil.getInstance().info("loanId[" + loanId + "]，获取进件扩展信息为空");
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("============LoanInfoService.synchronizeLoanApplyInfo 扩展信息同步异常," + loanId + "============", e);
		}
		
		info.setAccumulationFundNo("");// 无
		info.setAccumulationFundStatus(ac.getAccumulationFundStatus());
		info.setLoanId(loanId);
		String channel = ac.getChannelType();
		//info.setChannel(channel);
		info.setPatternCode("B");
		if ("101".equals(channel)) {
			//info.setChannelName("保险");
		} else if ("102".equals(channel)) {
			//info.setChannelName("银行");
		} else {
			//info.setChannelName("线上");
			info.setPatternCode("A");
		}
		info.setRemark("");
		if("101".equals(channel) || "102".equals(channel)) {
			try {} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("",e);
			}
		}
		info.setIsGoOffline(ac.getIsGoOffline());
		info.setApplyTerms(ac.getApplyTerms());
		info.setApplyTime(ac.getApplyTime());
		info.setPrincipalAmt(ac.getApplyMoney());
		info.setDecisionMoney(ac.getDecisionMoney());
		info.setStatus(ac.getStatus());
		info.setPurposeType(ac.getUsedCharacter());
		info.setPurposeCode(ac.getUsedId());
		info.setPurpose(ac.getUsedName());
		info.setPaymentBankHead("");
		info.setPaymentBankBranch("");
		info.setPaymentBankName(ac.getRepayBankName());
		info.setPaymentAcctName(ac.getRepayAcctName());
		info.setPaymentAcctNo(ac.getRepayAcct());
		info.setReceiveBankHead(ac.getBankLineNumberHeadOffice());
		info.setReceiveBankBranch(ac.getBankLineNumber());
		info.setReceiveBankName(ac.getReceiveBankName());
		info.setReceiveAcctName(ac.getReceiveAcctName());
		info.setReceiveAcctNo(ac.getReceiveAcct());
		info.setCreditRating(ac.getCreditLvl());
		info.setCustRating("");
		String workType = ac.getWorkType();
		info.setCustomerType(parseInt(workType));
		if ("1".equals(ac.getWorkType())) {
			String cType = ac.getCompanyType();
			if ("3".equals(cType)) {
				cType = "2";
			} else {
				cType = "1";
			}
			info.setSelfEmployedType(parseInt(cType));
			;// apply zigutype(自雇类型：1.公司 ，2.个体 自雇人士 必传)
		}

		info.setCustName(ac.getCustName());
		info.setMobileNo(ac.getMobileNum());
		info.setEmail(ac.getEmail());
		info.setQqNo(ac.getQqNo());
		info.setWeixinNo(ac.getWeixingNo());
		info.setCustSex(parseInt(ac.getSex()));
		info.setCustAge(ac.getAge());
		info.setCustBirthDate(ac.getBirthDate());
		info.setCustNationalityCode(null);
		info.setCustNationalityName(ac.getNationality());
		info.setCustCardType(null);
		info.setCustCardTypeName("身份证");
		info.setCustCardNo(ac.getCustIdCard());
		info.setCustCardIssuer(ac.getCertificateAuthority());
		info.setCustCardAddress(ac.getIdCardAddress());
		info.setCustCardStartTime(ac.getIdCardValidDate());
		info.setCustCardEndTime(ac.getIdCardValidEndDate());
		info.setCustHouseProvince(ac.getIdCardProvince());
		info.setCustHouseCity(ac.getIdCardCity());
		info.setCustHouseCounty(ac.getIdCardArea());
		info.setCustHouseAddr(ac.getIdCardAddress());
//		info.setCurHomeStartTime();
		info.setCurHomeProvince(ac.getProvinceId());
		info.setCurHomeProvinceName(ac.getProvinceName());
		info.setCurHomeCity(ac.getCityId());
		info.setCurHomeCityName(ac.getCityName());
		info.setCurHomeCounty(ac.getAreaId());
		info.setCurHomeCountyName(ac.getAreaName());
		info.setCurHomeAddress(ac.getAddress());
//		info.setHomeAddrSameHouse();
		info.setMaritalStatus(ac.getMarriageId());
		info.setMaritalStatusDesc(ac.getMarriageName());
		info.setSpouseName(ac.getMateName());
		info.setSpouseMobile(ac.getMateMobile());
		// info.setSpouseCardNo(null);
		// info.setSpouseCompanyName(null);
		// info.setSpouseWorkTel(null);
		// info.setSpouseEduLvlId(null);
		// info.setSpouseEduLvl(null);
		info.setChildrenCount(ac.getChildNumber());
		info.setSupportCount(ac.getSupportNumber());
		info.setEductionLevel(ac.getEducationLevel());
		info.setEductionLevelId(ac.getEducationLevelId() == null ? null : Integer.parseInt(ac.getEducationLevelId()));
		info.setHomeTypeId(ac.getLiveTypeId());
		info.setHomeType(ac.getLiveTypeName());
		info.setHomeRentStartDate(ac.getRentBeginDate());
		info.setHomeRentEndDate(ac.getRentEndDate());
		info.setHomeLivingTime(parseInt(ac.getLivingTime()));
		info.setHomeMthRent(ac.getRentMoney());
		info.setCompanyName(ac.getCompanyName());
		info.setCompanyTypeId(ac.getCompanyType());
		// info.setCompanyType();
		// info.setCompanyPost();
		info.setCompanyProvince(ac.getCompanyProvinceId());
		info.setCompanyProvinceName(ac.getCompanyProvinceName());
		info.setCompanyCity(ac.getCompanyCityId());
		info.setCompanyCityName(ac.getCompanyCityName());
		info.setCompanyCounty(ac.getCompanyAreaId());
		info.setCompanyCountyName(ac.getCompanyAreaName());
		info.setCompanyAddress(ac.getCompanyAddress());
		info.setCompanyOffice(ac.getOfficeSpaceType());
		info.setCompanyDept(ac.getWorkDept());
		info.setCompanyPositionType(ac.getPositionType());
		info.setCompanyPosition(ac.getPositionName());
		// info.setSelfMthIncoming(ac.getMonthlyIncome());
		info.setSelfMthIncomingCde(ac.getMonthlyIncomeId());
		info.setSelfMthIncomingName(ac.getMonthlyIncome());
		info.setSalaryPayDate(parseInt(ac.getSalaryDate()));
		info.setCompanyCode(ac.getBusinessLicense());
		info.setCompanyTel(ac.getOfficePhone());
		// info.setCompanyExtension(ac);
		info.setWorkLength(ac.getWorkYearsId());
		info.setWorkLengthName(ac.getWorkYearsName());
		// info.setCurCompanyDuration();
		info.setIndustryCde(ac.getVocation());
		// info.setIndustryName();
		info.setPersonnelDeptContactor(ac.getHrLinkman());
		// info.setPersonnelDeptContactorCode();
		info.setPersonnelDeptContactorTel(ac.getHrLinkmanPhone());
		// info.setPersonnelDeptContactorExtension();
		info.setCompanyRegistrationDate(ac.getCompanyRegisterTime());
		info.setShareholdingRate(ac.getShareholdingRatio());
		// info.setDecisionMoney(ac.getDecisionMoney());
		info.setRegisteredCapital(parseBig(ac.getRegistedAssets()));
		info.setBusinessLicenseNo(ac.getBusinessLicense());
		info.setBusinessLegalPerson(ac.getCorporation());
		info.setBusinessScope(ac.getBusinessScope());
		// info.setAffirmDebt(ac.getaff);
		// info.setCurrDebt();
		// info.setAffirmIncomes();
		// info.setSpecialRemark();
		// info.setPersentIncomesDebt();
		info.setFundCode(ac.getFundSource() == null ? "" : ac.getFundSource() + "");
		try {
			Map fundMap = mpFundPricingMapper.selectFundById(Long.valueOf(info.getFundCode()));
			info.setFundName(fundMap==null?"":(String)fundMap.get("description"));
		} catch (NumberFormatException e) { 
		}
		// info.setMinLoanBal();
		info.setProductType(ac.getProductType() + "");
		info.setProductTypeName(ac.getProductTypeName());
		// info.setPatternType);
		// info.setProductGroup();
		info.setProductCode(ac.getProductId());
		info.setProductName(ac.getProductName());
		// info.setRate(ac.getra);
		// info.setProductConsultingRate();
		// info.setProductManagementRate();
		info.setLoanCity(ac.getCityId());
		// info.setPricingType(ac.);
		info.setSocialSecurityNo(ac.getSocialSecurityComputer());
		info.setSocialSecurityStatus(ac.getSocialSecurityStatus());
		// info.setIntoPoolTime(ac.getinto);
		// info.setProjectName(ac.getpro);
		// info.setFjContractNo();''
		// info.setContractNo();
		// info.setCreatedBy();
		info.setCreatedDate(ac.getCreateTime());
		// info.setUpdatedBy();
		info.setUpdatedDate(ac.getUpdateTime());
		// info.setDeleteFlag();
		info.setCustCode(ac.getUserId());
		MarvelsLogUtil.getInstance().info("============LoanInfoService.synchronizeLoanApplyInfo end============");
		return info;
	}
	
	/**
	 * 获取保单信息
	 * 
	 * @param loanId
	 * @return
	 */
	@Override
	public List<McamAcLoanApplyBdInfo> synchronizeLoanApplyBxInfo(String loanId) {
		MarvelsLogUtil.getInstance().info("synchronizeInsurancePolicy ====>>loanId=" + loanId);
		List<AcLoanApplyBxInfo> acLoanApplyBdInfos = acLoanApplyBxInfoService.querybxInfo(loanId);// 保单信息
		if (acLoanApplyBdInfos == null || acLoanApplyBdInfos.size() == 0) {
			MarvelsLogUtil.getInstance().info("getAcLoanApplyBxInfos====>>保单信息为空==loanId==" + loanId);
		}
		MarvelsLogUtil.getInstance().info("synchronizeInsurancePolicy====>>info==" + acLoanApplyBdInfos.toString());
		List<McamAcLoanApplyBdInfo> list = new ArrayList<McamAcLoanApplyBdInfo>();
		for (AcLoanApplyBxInfo acInfo : acLoanApplyBdInfos) {
			McamAcLoanApplyBdInfo loanInfo = new McamAcLoanApplyBdInfo();
			loanInfo.setAdditionalInsuranceNum(acInfo.getAdditionalInsuranceNum());
			// 贷款编号
			loanInfo.setLoanId(acInfo.getLoanId());
			// 保单记录Id
			loanInfo.setInsuranceId("" + acInfo.getBxId());
			// 保险公司Id
			loanInfo.setInsuranceCpyCode(acInfo.getBxCompanyId());
			// 保险公司名称
			loanInfo.setInsuranceCpyName(acInfo.getBxCompanyName());
			// 主险名称
			loanInfo.setInsuranceName(acInfo.getBxName());
			// 保险类型
			loanInfo.setInsuranceType(acInfo.getBxType());
			// 寿险类型
			loanInfo.setLifeInsuranceType(acInfo.getLifeInsuranceType());
			// 保单状态
			loanInfo.setInsuranceStatus(acInfo.getBxStatus());
			// 保单生效日期
			loanInfo.setInsuranceEftDate(acInfo.getBxEffectiveDate());
			// 保单查询账户
			loanInfo.setInsuranceAccountName(acInfo.getBxAccountName());
			// 保单查询密码
			loanInfo.setInsuranceAccountPwd(acInfo.getBxAccountPwd());
			// 保单金额
			loanInfo.setInsuranceAmount(acInfo.getBxMoney());
			// 投保年限
			loanInfo.setInsuranceYears(acInfo.getBxYears());
			// 附加险数量
			loanInfo.setAdditionalInsuranceNum(acInfo.getAdditionalInsuranceNum());
			// 缴费方式Id
			loanInfo.setInsurancePayTypeCode(acInfo.getBxPayTypeId());
			// 缴费方式
			loanInfo.setInsurancePayTypeName(acInfo.getBxPayTypeName());
			// 年缴保费
			loanInfo.setInsuranceYearAmount(acInfo.getBxYearMoney());
			// 已缴期数
			loanInfo.setInsurancePayedTerms(acInfo.getBxPayedTerms());
			try {
				// 投保人是否有变更
				if(!StringUtils.isEmpty(acInfo.getIsChanged())){
					loanInfo.setPolicyholderChanged(Integer.parseInt(acInfo.getIsChanged()==
							null ? "" : acInfo.getIsChanged()));
				}
				if(!StringUtils.isEmpty(acInfo.getHasLoan())){
					// 保单是否存在保单贷款
					loanInfo.setInsuranceExistLoan(Integer.parseInt(acInfo.getHasLoan()
							== null ? "" : acInfo.getHasLoan()));
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("同步保单数据（投保人变更/保单是否存在保单贷款）异常----："+e);
			}
			// 保单编号
			loanInfo.setInsuranceNum(acInfo.getBxNum());
			// 保单类型Id
			loanInfo.setInsuranceTypeCode(acInfo.getBxTypeId());
			// 寿险分类Id
			loanInfo.setLifeInsuranceTypeCode(acInfo.getLifeInsuranceType());
			// 总期数
			loanInfo.setInsuranceTotalTerms(acInfo.getBxTotalTerms());
			// 投保人证件号码
			loanInfo.setPolicyholderIdCardNo(acInfo.getInsuredIdCard());
			// 投保人姓名
			loanInfo.setPolicyholderName(acInfo.getInsureByName());
			// 投保人联系电话
			loanInfo.setPolicyholderMobile(acInfo.getInsureByMobile());
			// 被投保人证件号码
			loanInfo.setInsuredPersonIdCardNo(acInfo.getInsuredIdCard());
			// 被投保人姓名
			loanInfo.setInsuredPersonName(acInfo.getInsuredName());
			// 被投保人联系电话
			loanInfo.setInsuredPersonMobile(acInfo.getInsuredMobile());
			// 期缴保额
			loanInfo.setInsuranceTermAmount(acInfo.getBxTermMoney());
			// 保险份数
			loanInfo.setInsuranceCount(acInfo.getBxCount());
			
			//
			Date createTime = acInfo.getCreateTime();
			Date updateTime = acInfo.getUpdateTime();
			loanInfo.setCreateTime(createTime);
			loanInfo.setUpdateTime(updateTime);
			list.add(loanInfo);
		}
		MarvelsLogUtil.getInstance().info("保单信息====>> list" + list);
		return list;
	}
	
	/**
	 * 获取映像文件
	 * 
	 * @param loanId
	 * @return
	 */
	@Override
	public List<McamAcLoanApplyImageInfo> synchronizeLoanApplyImageInfo(String loanId) {
		List<McamAcLoanApplyImageInfo> list = acLoanApplyInfoService.selectAttachmentInfo(loanId);
		AcLoanApplyInfo acLoan = queryLoanBasicInfo(loanId);
		if(acLoan!=null ) {
			// 蚂蚁贷就是线上产品
			String custIdCard = acLoan.getCustIdCard();
			// 同步云科贷的ocr实名认证信息
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.querByIdentiyCardNo(custIdCard);
			if (realNameAuthentication!=null) {
				McamAcLoanApplyImageInfo one = new McamAcLoanApplyImageInfo();
				one.setAtmtType("A");
				one.setAtmtTypeName("身份证");
				one.setFileLocation(realNameAuthentication.getIdcardimg1());
				one.setLoanId(loanId);
				McamAcLoanApplyImageInfo two = new McamAcLoanApplyImageInfo();
				two.setAtmtType("A");
				two.setAtmtTypeName("身份证");
				two.setFileLocation(realNameAuthentication.getIdcardimg2());
				two.setLoanId(loanId);
				McamAcLoanApplyImageInfo third = new McamAcLoanApplyImageInfo();
				third.setAtmtType("A");
				third.setAtmtTypeName("身份证");
				third.setFileLocation(realNameAuthentication.getPhoto());
				third.setLoanId(loanId);
				list.add(one);
				list.add(two);
				list.add(third);
			}
		}
		return list;
	}
	
	
	@Override
	public List<AcLoanApplyLinkman> queryLinkmanList(String loanId) {
		return acLoanApplyLinkmanService.queryLinkmanList(loanId);
	}

	@Override
	public Map<String, Object> queryLoanInfoByCondition(Map<String, Object> paramMap) {
		if(paramMap==null) return null;
		Integer pageNum = (Integer) paramMap.get("pageNum");
		Integer limit = (Integer) paramMap.get("limit");
		if (null == pageNum || pageNum < 1) {
			pageNum = 1;
		}
		if (null == limit || limit < 1) {
			limit = 20;
		}
		List<Order> orderList = new ArrayList<Order>();

		PageBounds pageBounds = new PageBounds(pageNum, limit, orderList);
		List<AcLoanApplyInfo> resultList = acLoanApplyInfoRepository.queryLoanInfoByCondition(paramMap, pageBounds);

		@SuppressWarnings("rawtypes")
		PageList pageList = (PageList) resultList;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		PageListJsonUtils.serialize(pageList, resultList, resultMap);
		return resultMap;
	}
	
	
	/**
	 * 查询贷款进度状态描述
	 * 
	 * @param loanStatus
	 *            贷款状态
	 * @return
	 */
	private PrCodeTable queryProgressRemark(String loanStatus) {
		Searchable searchable = Searchable.newSearchable();
		searchable.addSearchParam("typeId_eq", CASE_STATUS_TRACE_COCE);
		searchable.addSearchParam("id_eq", loanStatus);
		PrCodeTable prCodeTable = prCodeTableRepository.selectBySearchable(searchable);
		return prCodeTable;
	}
	
	private Integer parseInt(String value) {
		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			return 1;
		}
	}
	
	private BigDecimal parseBig(String value) {
		try {
			return new BigDecimal(value);
		} catch (Exception e) {
			return null;
		}
	}
	
	public boolean isValid(AcLoanApplyInfo loan) {
		String productType = loan.getProductType().toString();
		// 加个开关
		
		if ("1".equals(assureOnOff)) {
			return false;
		}

		if (ProductUtils.isKXG(productType) || ProductUtils.isXSS(productType) || ProductUtils.isXXSC(productType)) {
			return true;
		}
		Date passTime = null;
		List<AcCaseStatusTrace> loanProgerss = queryLoanProgerss(loan.getLoanId());
		for (AcCaseStatusTrace acCaseStatusTrace : loanProgerss) {
			if ("P01".equals(acCaseStatusTrace.getStatus())) {
				passTime = acCaseStatusTrace.getCreateTime();
				break;
			}
		}

		if (passTime == null)
			return false;

		String guaranteeRateStartDate = PropertiesLoadUtil.getPropertiesValue("yzy.guarantee.rate.start.date",
				"application.properties");
		if (StringUtils.isEmpty(guaranteeRateStartDate)) {
			return false;
		}
		Date parse = null;
		try {
			parse = new SimpleDateFormat("yyyyMMdd").parse(guaranteeRateStartDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (parse == null || passTime.before(parse)) {
			return false;
		}
		return true;
	}
	
	@Override
	public List<AcCaseStatusTrace> queryLoanProgerss(String loanId) {
		if (!StringUtils.hasText(loanId)) {
			return null;
		}
		List<String> statusList = prCodeTableRepository.selectIdByTypeId("NEED_STATUS");
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("loanId", loanId);
		paramMap.put("statusList", statusList);
		List<AcCaseStatusTrace> list = acCaseStatusTraceRepository.selectLoanProgerssByStatus(paramMap);

		// --------------------by nhy
		try {
			CmAppConsumptioninst cmAppConsumptioninst = appConsumptioninstService.findByLoanId(loanId);
			if (cmAppConsumptioninst != null) {
				String caseId = cmAppConsumptioninst.getCaseId();
				String needStatus = "P03SR0CR0ZR0";
				String decisionRejStatus = "SR1SR2SR3SR4";
				for (AcCaseStatusTrace acCaseStatusTrace : list) {
					if (needStatus.indexOf(acCaseStatusTrace.getStatus()) >= 0) {
						// 基于caseId 查询审批拒绝原因
						List<Map> rejectDescMapList = appConsumptioninstService.findRejectDescListByCaseId(caseId);
						List<String> rejectDescList = new ArrayList();
						for (Map rejectDescMap : rejectDescMapList) {
							String descId = (String) rejectDescMap.get("reject_code3_id");
							String descName = (String) rejectDescMap.get("reject_code3_name");
							if ("P03".equalsIgnoreCase(acCaseStatusTrace.getStatus()) && "T0101001".equals(descId)) {
								rejectDescList.add(descName);
							} else if (!"P03".equalsIgnoreCase(acCaseStatusTrace.getStatus())) {
								rejectDescList.add(descName);
							}
						}
						acCaseStatusTrace.setRejectAppDescList(rejectDescList);
					} else if (decisionRejStatus.indexOf(acCaseStatusTrace.getStatus()) >= 0) {
						// 进入这里的都是线下产品给决策拒绝的 要显示拒绝的细项
						String rejName = decisionGeneralRuleMapper.getRejNameByLoanId(loanId);
						acCaseStatusTrace.setDescription(rejName);
						acCaseStatusTrace.setRejectAppDesc(rejName);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if ("on".equals(prefixUrlSwitch)) {
			String longUrl = null;
			String status = "P05P06";
			for (AcCaseStatusTrace acCaseStatusTrace : list) {}
			for (AcCaseStatusTrace acCaseStatusTrace : list) {
				acCaseStatusTrace.setLongUrl(longUrl);

			}
		}
		return list;
	}
	
	@Override
	public Map<String, Object> selectAttributionByMobileSix(String mobile) {
		return acLoanApplyInfoRepository.selectAttributionByMobileSix(mobile);
	}
}
